﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ColorPickerSlider : MonoBehaviour
{
    public LabelSlider h;
    public LabelSlider s;
    public LabelSlider b;
    public Color color
    {
        set
        {
            float _h, _s, _b;
            Color.RGBToHSV(value, out _h, out _s, out _b);
            h.slider.value = _h;
            s.slider.value = _s;
            b.slider.value = _b;
        }
        get
        {
            return Color.HSVToRGB(h.slider.value, s.slider.value, b.slider.value);
        }
    }
    public Vector3 hsb
    {
        set
        {
            h.slider.value = value.x;
            s.slider.value = value.y;
            b.slider.value = value.z;
        }
        get
        {
            return new Vector3(h.slider.value, s.slider.value, b.slider.value);
        }
    }
    public Image colorViewer;
    public Image[] saturationLineSegments;
    public Action<float> onValueChanged;
    public bool editable
    {
        set
        {
            var sliders = GetComponentsInChildren<Slider>(true);
            foreach (var sld in sliders)
            {
                sld.enabled = value;
            }
        }
    }
    public void Init(Color origin, Action<float> action)
    {
        float _h, _s, _b;
        Color.RGBToHSV(origin, out _h, out _s, out _b);
        h.Init(_h, 0, 1, OnValueChanged);
        s.Init(_s, 0, 1, OnValueChanged);
        b.Init(_b, 0, 1, OnValueChanged);
        saturationLineSegments = transform.Search("SaturationLine").GetComponentsInChildren<Image>();
        SetSaturationColor();
        onValueChanged = action;
    }
    void OnValueChanged(float f)
    {
        if (onValueChanged != null) onValueChanged(f);
        hsb = new Vector3(h.slider.value, s.slider.value, b.slider.value);
        colorViewer.color = Color.HSVToRGB(hsb.x, hsb.y, hsb.z);
        SetSaturationColor();
    }
    void SetSaturationColor()
    {
        float _h, _s, _b;
        foreach (var segment in saturationLineSegments)
        {
            Color.RGBToHSV(segment.color, out _h, out _s, out _b);
            segment.color = Color.HSVToRGB(h.slider.value, _s, b.slider.value);
        }
    }
}
